/*
 * Realise par Thomas Moreau
 */
$(function($) {
	var selected = false;
	var cell_id = null;
	var my_turn = false;
	
	//met a jour les infos peripheriques a la matrice
	update_game_status = function() {
		$('#jouer-form').hide();
		if(state.ready == "False") {
			$('#game-status').html(" - En attente de joueurs...");
		} else {
			if(state.currentPlayer != state.playerNbr) {
				var n = parseInt(state.currentPlayer) + 1;
				$('#game-status').html(" - Le joueur " + n  + " joue...");
			} else {
				my_turn = true;
				$('#jouer-form').show();
				$('#game-status').html(" - A vous de jouer !");
			}
		}
	};
	update_game_status();
	
	//quand on clique sur une des balises <td>
	$("#matrice > tbody > tr > td").click(function(){
		if(state.ready != "False" && my_turn) {
			if(!selected && $(this).children('img').attr('class') != "letter") {
				cell_id = $(this).attr('id');
				$(this).html('<input type="text" autofocus="" maxlength="1"/>');
				selected = true;
				$('#' + cell_id).focus();
			} else if (selected && $(this).attr('id') != cell_id && $(this).children('img').attr('class') != "letter") {
				$("#" + cell_id).html('<img class="nothing" src="/static/img/letters/null.png" alt="letter"/>');
				cell_id = $(this).attr('id');
				$(this).html('<input type="text" autofocus="" maxlength="1"/>');
				$('#' + cell_id).focus();
			}
		}
    });
	
	//action : jouer un coup
	$("#btn_jouer").click(function() {
		var coords = cell_id.split("A");
		if($("#" + cell_id).children('input').val() != ""){
			$.post("/game/" + state.game_key + "/joue", { ligne: coords[0], colonne: coords[1], lettre: $("#" + cell_id).children('input').val().toLowerCase(), mot: $("#input_playedword").val() } );
		}
	});
	
	//action : passer au lieu de jouer
	$("#btn_passer").click(function() {
		$.post("/game/" + state.game_key + "/passe");
	});
	
	//actualise seulement les parties de la page modifiees, et non toute la page.
	update_game = function(mess) {
		if(cell_id != null) {
			$("#" + cell_id).html('<img class="nothing" src="/static/img/letters/null.png" alt="letter"/>');
		}
		$("#" + mess.ligne + "A" + mess.colonne).html('<img class="letter" src="/static/img/letters/' + mess.lettre + '.png" alt="letter"/>');
		
		//scores
		var content = "";
		for(var i = 0 ; i < mess.scores.length ; i++) {
			content += '<p style="font-size:20px;"><strong>Joueur ' + (i+1) + '</strong> : <span id="score_' + (i+1) + '">' + mess.scores[i] + '</span> points</p>';
		}
		$('#list-scores').html(content);
		
		//mots
		$('#list-mots').append('<p style="font-size:12px;"><strong>' + mess.lastWord + '</strong></p>');
		$('#list-mots').animate({scrollTop : $('#list-mots').prop('scrollHeight')}, 50);
		
		selected = false;
		cell_id = null;
		my_turn = false;
		update_game_status();
	}
	
	// CHANNEL
	onMessage = function(m) {
		//alert(m.data);
		var mess = JSON.parse(m.data);
		if(mess.event == "update_game") {
			$('#wrong-word').html("");
			var n = parseInt(state.currentPlayer) + 1;
			if(n == parseInt(state.nbPlayers)) {
				n = 0;
			}
			state.currentPlayer = n.toString();
			update_game(mess);
		} else if(mess.event == "error") {
			$('#wrong-word').html(mess.erreur);
		} else if(mess.event == "ready_to_play") {
			$('#wrong-word').html("");
			state.ready = true;
			update_game_status();
		} else if(mess.event == "passe") {
			$('#wrong-word').html("");
			var n = parseInt(state.currentPlayer) + 1;
			if(n == parseInt(state.nbPlayers)) {
				n = 0;
			}
			state.currentPlayer = n.toString();
			update_game(mess);
		} else if(mess.event == "game_over") {
			$('#wrong-word').html("");
			var n = parseInt(mess.winner) + 1;
			$('#main-panel').html('<h2>Partie Terminee :</h2> <p><strong>Le Joueur ' + n + ' gagne la partie !</strong></p><a href="/room">Revenir a la salle de jeu</a>');
			$('#jouer-form').hide();
		}
	};
	
	var channel = new goog.appengine.Channel(token);
	var handler = {
		'onopen' : function() {
		},
		'onmessage' : onMessage,
		'onerror' : function() {
		},
		'onclose' : function() {
		}
	};
	var socket = channel.open(handler);
	socket.onmessage = onMessage;
	//END CHANNEL
})(jQuery);